﻿#define DEBUG_AGENT

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SpaceNeedle.x6473.WindowsPhone.ViewModels;
using SpaceNeedle.x6473.WindowsPhone.Common;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Scheduler;
using System.Net.NetworkInformation;
using Windows.Networking.Connectivity;
using SpaceNeedle.SDK.WindowsPhone.Views;
using System.Device.Location;
using Microsoft.Phone.Maps.Controls;
using Microsoft.Phone.Maps.Toolkit;
using SpaceNeedle.x6473.WindowsPhone.Models;
using System.Globalization;
using SpaceNeedle.SDK.WindowsPhone;
using System.Windows.Threading;
using System.Windows.Media.Imaging;

namespace SpaceNeedle.x6473.WindowsPhone.Views
{
    public class HomeView : ViewBase<HomeViewModel> { }

    public partial class Home : HomeView
    {
        public bool agentsAreEnabled = true;

        private List<GeoCoordinate> requestItemsCoordinates = new List<GeoCoordinate>();
        private bool canChangeMapZoom = false;

        public Home()
        {
            InitializeComponent();

            this.ViewModel.Loaded += ViewModel_Loaded;
            this.ViewModel.RatingRequested += ViewModel_RatingRequested;
            this.map.Loaded += map_Loaded;
            this.map.ViewChanged += map_ViewChanged;

            this.timerZoom.Tick += timerZoom_Tick;
            this.timerZoom.Interval = TimeSpan.FromSeconds(1);

            this.Loaded += Home_Loaded;
        }

        private async void ViewModel_RatingRequested()
        {
            if(MessageBox.Show("Obrigado por utilizar o " + this.ViewModel.AppContent.Name + ", gostaria de avaliá-lo agora?", this.ViewModel.AppContent.Name, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                AppViewModel.Instance.Properties.IsRatingActivated = true;
                AppViewModel.Instance.Properties.IsRatingDeclined = false;

                var task = new MarketplaceReviewTask();
                task.Show();

                Tracking.SendEvent("Avaliação", "Ativada", "Aplicativo Avaliado", 0);
            }
            else
            {
                Tracking.SendEvent("Avaliação", "Cancelada", "Avaliação Cancelada", 0);
            }

            await AppViewModel.Instance.SaveAppState();
        }

        void Home_Loaded(object sender, RoutedEventArgs e)
        {
            this.ShowContextualAppBar();
        }

        void timerZoom_Tick(object sender, EventArgs e)
        {
            this.timerZoom.Stop();

            this.map.SetView(this.map.Center, this.map.ZoomLevel - 1);
        }

        private DispatcherTimer timerZoom = new DispatcherTimer();

        void map_ViewChanged(object sender, MapViewChangedEventArgs e)
        {
            if(this.canChangeMapZoom)
            {
                this.canChangeMapZoom = false;
                this.timerZoom.Start();
            }
        }

        void map_Loaded(object sender, RoutedEventArgs e)
        {
            
        }


        private void RemoveAgent(string name)
        {
            try
            {
                ScheduledActionService.Remove(name);
            }
            catch (Exception)
            {

            }
        }

        async void ViewModel_Loaded()
        {
          //  var coord = await AppServices.Current.LocationService.GetGeopositionAsync();

            //this.map.Center = new GeoCoordinate(coord.Coordinate.Latitude.Value, coord.Coordinate.Longitude.Value);
            this.map.Center = new GeoCoordinate(-23.4848646,-46.8647897);
            
            this.map.ZoomLevel = 14;

            if (this.ViewModel.RequestItems == null)
            {
                return;
            }

            this.requestItemsCoordinates = new List<GeoCoordinate>();

            foreach (var item in this.ViewModel.RequestItems)
            {
                if (string.IsNullOrEmpty(item.Geoposition))
                {
                    continue;
                }

                MapLayer layer = new MapLayer();
                Pushpin pushpin = new Pushpin();

                //pushpin.Content = new Image() { Source = new BitmapImage(new Uri(item.RequestIcon)), Width = 48 };

                StackPanel stack = new StackPanel();
                stack.Orientation = System.Windows.Controls.Orientation.Horizontal;

                Image pushpinIcon = new Image() { Source = new BitmapImage(new Uri(item.RequestIcon)), Width = 48 };
                stack.Children.Add(pushpinIcon);

                TextBlock textBlock = new TextBlock();
                textBlock.Text = item.TotalSupportersCount.ToString();
                stack.Children.Add(textBlock);

                pushpin.Content = stack;

                //pushpin.Content = new Image() { Source = new BitmapImage(new Uri(item.RequestIcon)), Width = 48 };
                pushpin.Tap += pushpin_Tap;
                pushpin.Tag = item;

                MapOverlay overlay = new MapOverlay();
                overlay.Content = pushpin;

                string[] parts = item.Geoposition.Split(',');

                if (parts.Length == 2)
                {
                    overlay.GeoCoordinate = new GeoCoordinate(ConvertToDouble(parts[0]), ConvertToDouble(parts[1]));
                    this.requestItemsCoordinates.Add(overlay.GeoCoordinate);

                    layer.Add(overlay);
                    map.Layers.Add(layer);
                }
            }

            if (this.requestItemsCoordinates != null && this.requestItemsCoordinates.Count > 0)
            {
                this.canChangeMapZoom = true;
                map.SetView(LocationRectangle.CreateBoundingRectangle(this.requestItemsCoordinates));
            }
        }

        void pushpin_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Pushpin pushpin = sender as Pushpin;
            RequestItem item = pushpin.Tag as RequestItem;

            AppViewModel.Instance.Properties.SelectedRequestItem = item;
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.RequestItemDetails);
        }

        private double ConvertToDouble(string number)
        {
            number = number.ToString().Replace(",", ".");

            if (string.IsNullOrEmpty(number))
            {
                return 0;
            }

            NumberFormatInfo provider = new NumberFormatInfo();
            provider.NumberDecimalSeparator = ".";
            provider.NumberGroupSeparator = ",";

            return System.Convert.ToDouble(number, provider);
        }

        private void OnAboutMenuItem_Click(object sender, EventArgs e)
        {
            this.ViewModel.AboutCommand.Execute(null);
        }

        private void OnSettingsMenuItem_Click(object sender, EventArgs e)
        {
            this.ViewModel.SettingsCommand.Execute(null);
        }

        private void OnUploadsMenuItem_Click(object sender, EventArgs e)
        {
            this.ViewModel.UploadsCommand.Execute(null);
        }

        private void OnCallAppBarButton_Click(object sender, EventArgs e)
        {
            SpaceNeedle.x6473.WindowsPhone.Models.Phone phone = new Models.Phone();

            phone.Title = ViewModel.StaticContent.CentralTitle;
            phone.Number = ViewModel.StaticContent.CentralNumber;

            this.ViewModel.DialCommand.Execute(phone);
        }
        
        private void OnNewRequest_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.NewRequest);
        }

        private void OnTicketsHeader_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Tickets);
        }

        private void OnAlertsHeader_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Alerts);
        }

        private void OnCallsHeader_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Calls);
        }

        private void OnFacebookImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Social + "?goto=0");
            Tracking.SendEvent("Social", "Facebook", "Posts de Facebook Visualizados", 0);
        }

        private void OnTwitterImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Social + "?goto=1");
            Tracking.SendEvent("Social", "Twitter", "Posts de Twitter Visualizados", 0);
        }

        private void OnUserTicketsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0)
            {
                return;
            }

            AppViewModel.Instance.Properties.SelectedRequestItem = e.AddedItems[0] as Models.RequestItem;
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.RequestItemDetails);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            while (this.NavigationService.BackStack.Any())
            {
                this.NavigationService.RemoveBackEntry();
            }
        }

        private void OnUsefulNumbersListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(e.AddedItems.Count == 0)
            {
                return;
            }

            this.ViewModel.DialCommand.Execute(e.AddedItems[0]);

            usefulNumbersListBox.SelectedIndex = -1;
        }

        private void OnClearAlertsAppBarButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Tem certeza que deseja limpar a lista de Alertas?", "Alertas", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                this.ViewModel.ClearAlertsCommand.Execute(null);
            }
        }

        private void OnShareTicket_Click(object sender, RoutedEventArgs e)
        {
            RequestItem item = (sender as MenuItem).Tag as RequestItem;

            ShareLinkTask shareLinkTask = new ShareLinkTask();
            shareLinkTask.LinkUri = new Uri(item.Permalink, UriKind.Absolute);
            shareLinkTask.Message = item.Description;

            shareLinkTask.Show();
        }

        private void OnSignOutMenuItem_Click(object sender, EventArgs e)
        {
            this.ViewModel.SignOutCommand.Execute(null);
        }

        private void OnHomePanorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.ShowContextualAppBar();
        }

        private void ShowContextualAppBar()
        {
            if (homePanorama.SelectedIndex == 3)
            {
                ApplicationBar = ((ApplicationBar)this.Resources["appbarFull"]);
            }
            else if(homePanorama.SelectedIndex == 1)
            {
                ApplicationBar = ((ApplicationBar)this.Resources["appbarMap"]);
            }
            else
            {
                ApplicationBar = ((ApplicationBar)this.Resources["appbarHalf"]);
            }
        }

       
        private void OnMap_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Calls);
        }

        private void OnRequestsAppBarButton_Click(object sender, EventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Calls);
        }

        private void OnCityDetailsHeader_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.CityDetails);
        }
    }
}